package com.ms.commons.utils;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author:SmartV
 * @date:2021/11/24 10:54
 */
public class BaseMapperImpl<M extends BaseMapper<T>,T> extends ServiceImpl {
    /**
     * D dto的类 t,实体类
     * @param dto
     * @param tClass
     * @param <D>
     */
    public <D> boolean  dtoAdd(D dto,Class<T> tClass){
        try {
            T entity = tClass.newInstance();
            BeanUtils.copyProperties(dto,entity);
            int insert = baseMapper.insert(entity);
            return insert>0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public Page<T> getPage(){
        //当前页 第一页
        // 每页15条
        return new Page(1,15);
    }

    public <V> PageResult<T> pageList(LambdaQueryChainWrapper<T> where,Class<V> vClass){
        IPage<V> page= voList(where,vClass);
        //当前页 第一页
        // 每页15条
        return new PageResult(page.getTotal(),page.getRecords());
    }

    private <V> IPage<V> voList(LambdaQueryChainWrapper<T> where, Class<V> vClass) {
        IPage<T> page = page(getPage(), where);
        List<V> voList = page.getRecords().stream().map(item -> {
            V vo = null;
            try {
                vo = vClass.newInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }
            BeanUtils.copyProperties(item, vo);
            return vo;
        }).collect(Collectors.toList());
        IPage<V> page1 = new Page<>();
        BeanUtils.copyProperties(page,page1);
        page1.setRecords(voList);
        return page1;

    }
}
